/*
 * 对文件进行切片上传 
 */
var file;
var fileInput = document.querySelector('#fileInput');
var progressText = document.querySelector('#progress-text');
var sliceList = [];
var urlList = [];
var videoId = "";
var etagList = [];
var retryTimes = 3;
var failedList = [];
var index = 0; //当前上传的切片数目
var successIndex = 0; //当前上传成功的切片数目

fileInput.addEventListener("change", function() {
	file = this.files[0];
	progressText.innerText = "0/0";
});

function uploadFile() {
	var regionCode = document.querySelector('#regionCode').value;
	if(!regionCode || !file) {
		alert("参数不能为空！");
		return;
	}
	
	failedList = [];
	index = 0;
	successIndex = 0;
	var params = {};
	params.regionCode = regionCode;
	params.name = file.name;
	params.fileInfo = {
		mad5: "",
		fileSize: file.size,
		partSize: 10 * 1024 * 1024
	};
	$.ajax({
		url: "/video/create",
		type: "POST",
		contentType: "application/json",
		data: JSON.stringify(params),
		dataType: "json",
		success: function(response) {
			var res = JSON.parse(response);
			if(res.code == "0") {
				var data = res.data;
				urlList = data.uploadUrls;
				videoId = data.videoId;
				sliceList = sliceFile(file, urlList.length, params.fileInfo.partSize);//切割文件
				progressText.innerText = "0/" + sliceList.length;
				sendFileSlice(sliceList, urlList);//上传文件切片
			} else {
				alert(res.message);
			}
		},
		error: function(status) {
			
		}
	});
}

function sendFileSlice(sliceList, urlList) {
	var len = sliceList.length;
	$.ajax({
		url: urlList[index],
		type: "put",
		contentType: "binary/octet-stream",
		data: sliceList[index],
		processData: false,   // jQuery不要去处理发送的数据
		success: function(responseText,status,xhr) {
			var etag = xhr.getResponseHeader('etag')
			etagList.push({
				partNumber: index + 1,
				eTag: etag.replace(/\"/g, "")
			});
			index = index + 1;
			successIndex = successIndex + 1;
			progressText.innerText = successIndex + "/" + len;
			if(index < len) {
				sendFileSlice(sliceList, urlList);
			} 
			if(successIndex  == len) {
				completeUpload(videoId, etagList);
				index = 0;
				etagList = [];
			}
		}
		,
		error: function(xhr, textStatus, errorThrown) {  
			//重传机制
			if(failedList.length == 0 || failedList[failedList.length - 1].partNumer != index + 1) {
				var failedObj = {
					partNumber: index + 1,
					retry: 0
				};
				failedList.push(failedObj);
			}
			
			var retryObj = failedList[failedList.length - 1];
			if(retryObj.retry < retryTimes) {
				retryObj.retry++;
				sendFileSlice(sliceList, urlList);
			} else {
				index = index + 1;
				if(index < sliceList.length) {
					sendFileSlice(sliceList, urlList);
				}
			}
		}
		
	});
		
}

function sliceFile(file, sliceNum, sliceSize) {
	var sliceList = [];
	var start = 0;
	var end = file.size;
	for(var i = 0; i < sliceNum; i++) {
		var slicePoint = Math.min(start + sliceSize, end);
		sliceList[i] = file.slice(start, slicePoint);
		start = start + sliceSize;
	}
	return sliceList;
}

function completeUpload(videoId, etagList) {
	var params = {};
	params.videoId = videoId;
	params.etags = etagList;
	$.ajax({
		url: "/video/complete",
		type: "post",
		contentType: "application/json",
		data: JSON.stringify(params),
		dataType: "json",
		success: function(responseText) {
			var res = JSON.parse(responseText);
			if(res.code == "0") {
				alert("文件上传成功！")
			} else {
				alert(res.message);
			}
		},
		error: function(status) {
			
		}
	});
}